﻿using Common.Communal;
using ERP.Domain.Workorders.Inventory;
using MediatR;
using Product.API.Read.Applications.Commands.WorkOrder.Inventory;
using SqlSugar;

namespace Product.API.Read.Applications.CommandHandlers.WorkOrder.Inventory
{
    /// <summary>
    /// 库存入库出库显示命令处理
    /// </summary>
    public class InventoryTransactionWorkOrderShowCommandHandler : IRequestHandler<InventoryTransactionWorkOrderShowCommand, ApiResult<ApiPaging<InventoryTransactionWordOrder>>>
    {
        /// <summary>
        /// SqlSugar
        /// </summary>
        private readonly ISqlSugarClient db;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db">SqlSugar</param>
        public InventoryTransactionWorkOrderShowCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<ApiResult<ApiPaging<InventoryTransactionWordOrder>>> Handle(InventoryTransactionWorkOrderShowCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<InventoryTransactionWordOrder>> result = new ApiResult<ApiPaging<InventoryTransactionWordOrder>>();
            result.Code = EnumCode.Ok;
            result.Message = EnumCode.Ok.ToString();

            int totalPage = 0;
            int totalCount = 0;
            var data = db.Queryable<InventoryTransactionWordOrder>().ToPageList(request.pageIndex, request.pageSize, ref totalCount, ref totalPage).ToList();

            if (request.wareHouseName != null)
            {
                data = data.Where(x => x.WarehouseName.Contains(request.wareHouseName)).ToList();
            }

            if (request.productName != null)
            {
                data = data.Where(x => x.ProductName.Contains(request.productName)).ToList();
            }

            if (request.productType != null)
            {
                data = data.Where(x => x.ProductType.Contains(request.productType)).ToList();
            }

            if (request.unit != null)
            {
                data = data.Where(x => x.Unit.Contains(request.unit)).ToList();
            }

            ApiPaging<InventoryTransactionWordOrder> page = new ApiPaging<InventoryTransactionWordOrder>();
            page.TotalCount = totalCount;
            page.TotalPage = totalPage;
            page.Data = data;

            result.Data = page;
            return Task.FromResult(result);
        }
    }
}
